package cn.android666.nopreviewcamera

import timber.log.Timber
import java.util.concurrent.ArrayBlockingQueue

import java.util.concurrent.BlockingQueue
import java.util.concurrent.TimeUnit


class H264SaverThread : Thread(TAG) {
    @Suppress("SpellCheckingInspection")
    private var mYUVDatasQueue: BlockingQueue<H264Data> = ArrayBlockingQueue(1)
    private val mH264Saver = H264Saver()
    private var frameLossCount: Int = 0
    private var needRun = true

    @Suppress("SpellCheckingInspection")
    fun addYUVDatas(yuvDatas: H264Data) {
        if (needRun) {
            val offer = mYUVDatasQueue.offer(yuvDatas)
            if (!offer) {
                ++frameLossCount
                Timber.w("丢帧：${frameLossCount}帧")
            }
        }
    }

    override fun run() {
        try {
            while (needRun) {
                mYUVDatasQueue.poll(30L, TimeUnit.MILLISECONDS)?.let {
                    if (needRun) {
                        mH264Saver.saveToFile(it)
                    }
                }
            }
        } catch (e: Exception) {
            Timber.e(e,"把YUV编码为H264时出现异常")
        }
    }

    fun close() {
        try {
            needRun = false
            mH264Saver.close()
        } catch (e: Exception) {
            Timber.w(e, "关闭H264编码器时出现异常")
        }
    }

    companion object {
        private val TAG = H264SaverThread::class.java.simpleName
    }

}